package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.animationType;
import static com.mingtu.jgspatrol.utils.MyConstant.isFirstOnly;
import static com.mingtu.jgspatrol.utils.MyConstant.isOpenLoadAnimation;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.center.adapter.DepartmentAdapter;
import com.mingtu.center.bean.DeptNameBean;
import com.mingtu.common.base.BaseBindingActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.CalendarPickerUtils;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.UIUtils;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.view.FilterCancleView;
import com.mingtu.common.view.FilterSureView;
import com.mingtu.common.view.TimeFilterView;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.AllRecordTrackAdapter;
import com.mingtu.jgspatrol.bean.AllTrackRecordBean;
import com.mingtu.jgspatrol.databinding.ActivityTrackRecordBinding;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class TrackRecordActivity extends BaseBindingActivity<ActivityTrackRecordBinding> {
    private String beginTime;
    private String endTime;
    private boolean departFlag = false; //记录部门是否展开
    private List<String> deptIdList;
    private DepartmentAdapter departmentAdapter;
    private List<DeptNameBean.ListBean> myDepartBeans;
    private AllRecordTrackAdapter allRecordTrackAdapter;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private List<DeptNameBean.ListBean> departBeans;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_track_record;
    }

    @Override
    protected void initView() {
        setModuleTitle("巡护记录");
        showTopRightImg(R.mipmap.icon_filte);
    }

    @Override
    protected void initData() {

        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        binding.recycler.setLayoutManager(manager1);
        binding.recycler.addItemDecoration(new BottomSpaceItemDecoration());

        allRecordTrackAdapter = new AllRecordTrackAdapter();

        if (isOpenLoadAnimation) {
            allRecordTrackAdapter.isFirstOnly(isFirstOnly);
            allRecordTrackAdapter.openLoadAnimation(animationType);
        }

        allRecordTrackAdapter.setEmptyView(new EmptyDataLayout(context));
        binding.recycler.setAdapter(allRecordTrackAdapter);
        allRecordTrackAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int trackId = allRecordTrackAdapter.getData().get(position).getId();
                Bundle bundle = new Bundle();
                bundle.putString("trackId", String.valueOf(trackId));
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), TrackDetailsActivity.class, bundle);
            }
        });


        //保护站列表
        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(this);
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        binding.recyclerDepart.setLayoutManager(flm1);

        departmentAdapter = new DepartmentAdapter(context, null);
        binding.recyclerDepart.setAdapter(departmentAdapter);


        binding.timeFilterTime.setOnTimeResultListener(new TimeFilterView.OnTimeResultListener() {
            @Override
            public void onResult(Date startDate, Date endDate) {
                beginTime = UIUtils.getTime3(startDate);
                endTime = UIUtils.getTime3(endDate);
            }
        });

        binding.filterCancleView.setOnClickListener(new FilterCancleView.OnClickListener() {
            @Override
            public void onClickCancel() {
                closeDrawers();
            }
        });

        binding.filterSureView.setOnClickListener(new FilterSureView.OnClickListener() {
            @Override
            public void onClickReset() {
                closeDrawers();
                resetData();
                CalendarPickerUtils.getInstance().resetData();
            }

            @Override
            public void onClickSure() {
                closeDrawers();
                deptIdList = departmentAdapter.getDeptIdList();
                getTrackRecordList(1);
            }
        });

        addClickListener(this, binding.layoutArrowDepart);

    }

    @Override
    protected void getData() {
        initListener();
        getDeptList();
        getTrackRecordList(1);
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        boolean isOpen = binding.drawerLayout.isDrawerOpen(binding.layoutRightDrawer);
        if (isOpen) {
            closeDrawers();
        } else {
            openDrawer();
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.layout_arrow_depart:
                if (departFlag) { //默认为false,收起状态
                    departFlag = false;
                    binding.tvFoldDepart.setText("展开");
                    departmentAdapter.upData(myDepartBeans);
                } else {
                    departFlag = true;
                    binding.tvFoldDepart.setText("收起");
                    departmentAdapter.upData(departBeans);
                }
                break;

        }
    }


    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        binding.srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.srlUp.finishRefresh(Constant.REFRESH_TIME);
                binding.srlUp.setNoMoreData(false);
                currentPage = 1;
                getTrackRecordList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        binding.srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(allRecordTrackAdapter.getData(), Constant.PAGE_SIZE);
                    getTrackRecordList(currentPage);
                }
                binding.srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 关闭侧边栏
     */
    public void closeDrawers() {
        binding.drawerLayout.closeDrawer(binding.layoutRightDrawer, true);
    }

    /**
     * 打开侧边栏
     */
    public void openDrawer() {
        binding.drawerLayout.openDrawer(binding.layoutRightDrawer);
    }

    /**
     * 获得巡护记录的部门名字数据
     */
    private void getDeptList() {
        OkGo.<String>post(Constant.getInstance().POST_DEPT_LIST2)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                DeptNameBean deptNameBean = new DeptNameBean();
                                deptNameBean = gson.fromJson(result, DeptNameBean.class);

                                if (deptNameBean != null) {
                                    departBeans = deptNameBean.getList();
                                    if (departBeans != null) {
                                        if (departBeans.size() > 0) {

                                            if (departBeans.size() > 6) {
                                                //数据大于6的时候，取前6条数据，有展开收回操作
                                                myDepartBeans = departBeans.subList(0, 6);
                                                departmentAdapter.upData(myDepartBeans);
                                                binding.layoutArrowDepart.setVisibility(View.VISIBLE);

                                            } else {
                                                //数据个数小与6的时候，展开视图隐藏
                                                departmentAdapter.upData(departBeans);
                                                binding.layoutArrowDepart.setVisibility(View.GONE);
                                            }

                                        }
                                    }
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    private void resetData() {
        departmentAdapter.resetData();
        beginTime = null;
        endTime = null;
        deptIdList = null;
        binding.timeFilterTime.resetData();
        getTrackRecordList(1);
    }


    /**
     * 获得巡护人员数据
     */
    public void getTrackRecordList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("deptIdList", deptIdList);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_TRACK_RECORD_ALL)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                AllTrackRecordBean allTrackRecordBean = new AllTrackRecordBean();
                                allTrackRecordBean = gson.fromJson(result, AllTrackRecordBean.class);

                                AllTrackRecordBean.DataBean dataBean = allTrackRecordBean.getData();
                                AllTrackRecordBean.DataBean.PageBean pageBean = dataBean.getPage();
                                List<AllTrackRecordBean.DataBean.PageBean.ListBean> listBeans = pageBean.getList();

                                AllTrackRecordBean.DataBean.StaticsBean staticsBean = dataBean.getStatics();


                                try {
                                    if (listBeans != null) {
                                        isLoadMore = listBeans.size() > 0 && listBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            allRecordTrackAdapter.replaceData(listBeans);
                                        } else {
                                            allRecordTrackAdapter.addData(listBeans);
                                        }
                                    }

                                    if (staticsBean != null && currentPage == 1) {
                                        int totalMileage = staticsBean.getTotalMileage();
                                        String duration = staticsBean.getTotalDuration();
                                        String totalCount = staticsBean.getTotalCount();

                                        binding.tvTotalMileage.setText(totalMileage + "");

                                        if (!StringUtils.isEmpty(totalCount)) {
                                            binding.tvTotalDayNum.setText(totalCount + "");
                                        } else {
                                            binding.tvTotalDayNum.setText("0");
                                        }

                                        if (!StringUtils.isEmpty(duration)) {
                                            long d = 0;
                                            if (duration.indexOf(".") != -1) {
                                                String array[] = duration.split("\\.");
                                                d = Long.parseLong(array[0]);
                                            } else {
                                                d = Long.parseLong(duration);
                                            }
                                            binding.tvTotalTime.setText(MyUtills.formatSeconds2(d));
                                        } else {
                                            binding.tvTotalTime.setText("0");
                                        }


                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }

                        }
                    }
                });
    }
}